﻿using Kingdee.BOS;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.NotePrint;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.ServicesStub;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fibot.YGJD.K3Cloud.Webapi
{
    public class PDFApi : AbstractWebApiBusinessService
    {
        public PDFApi(KDServiceContext context) : base(context)
        {
        }

        public string GetPDFUrl(string id, string templateId, string formId)
        {
            try
            {
                templateId = "";
                string fileName = ExportTargetBill(formId, id, templateId);
                string url = System.Web.HttpContext.Current.Request.Url.Scheme + "://" +
                             System.Web.HttpContext.Current.Request.Url.Authority + "/K3Cloud/" + KeyConst.TEMPFILEPATH +
                             "/" + fileName;
                return url;
            }
            catch (Exception ex)
            {
                return "发生异常：" + ex.Message;
            }
        }


        /// <summary>
        /// 套打导出指定单据
        /// </summary>
        /// <param name="formId"></param>
        /// <param name="billId"></param>
        /// <param name="templateId"></param>
        /// <returns></returns>
        private string ExportTargetBill(string formId, string billId, string templateId)
        {
            IDynamicFormView dynamicFormView = CreateView(this.KDContext.Session.AppContext, formId, billId); //此行为代码模拟打开凭证界面
            if (dynamicFormView == null)
                return null;
            try
            {
                return ExportTargetBill(dynamicFormView, formId, billId, templateId);
            }
            finally
            {
                dynamicFormView.Close();
            }
        }

        private string ExportTargetBill(IDynamicFormView dynamicFormView, string formId, string billId, string templateId)
        {
            Kingdee.BOS.Core.Import.IImportView importView = dynamicFormView as Kingdee.BOS.Core.Import.IImportView;
            IDynamicFormViewService viewService = dynamicFormView as IDynamicFormViewService;
            if (importView == null || viewService == null)
                return null;
            try
            {
                importView.AddViewSession();

                List<string> billIds = new List<string>() { billId };
                List<string> templateIds = new List<string>() { templateId };

                PrintExportInfo pExInfo = new PrintExportInfo();
                pExInfo.PageId = dynamicFormView.PageId;
                pExInfo.FormId = formId;
                pExInfo.BillIds = billIds; //单据内码
                pExInfo.TemplateIds = templateIds; //套打模板ID
                pExInfo.FileType = ExportFileType.PDF; //文件格式
                pExInfo.ExportType = ExportType.ByPage; //导出格式
                string fileName = Guid.NewGuid().ToString() + ".PDF";
                string temppath = PathUtils.GetPhysicalPath(KeyConst.TEMPFILEPATH, fileName);
                pExInfo.FilePath = temppath; //文件输出路径
                
                viewService.ExportNotePrint(pExInfo);
                return fileName;
            }
            finally
            {
                importView.RemoveViewSession();
            }
        }

        #region 创建服务端视图（引入视图）
        /// <summary>
        /// 构建表单打开参数
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="metadata"></param>
        /// <param name="pkValue"></param>
        /// <returns></returns>
        private BillOpenParameter CreateOpenParameter(Context ctx, FormMetadata metadata, string pkValue)
        {
            var form = metadata.BusinessInfo.GetForm();
            BillOpenParameter openPara = new BillOpenParameter(form.Id, metadata.GetLayoutInfo().Id);
            openPara.Context = ctx;
            openPara.PageId = Guid.NewGuid().ToString();
            openPara.Status = OperationStatus.VIEW;
            openPara.CreateFrom = CreateFrom.Default;
            openPara.DefaultBillTypeId = string.Empty;
            openPara.PkValue = pkValue;
            openPara.FormMetaData = metadata;
            openPara.SetCustomParameter(Kingdee.BOS.Core.FormConst.PlugIns, form.CreateFormPlugIns());
            openPara.ServiceName = form.FormServiceName;
            return openPara;
        }

        /// <summary>
        /// 创建视图
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="formId"></param>
        /// <param name="pkValue"></param>
        /// <returns></returns>
        private IDynamicFormView CreateView(Context ctx, string formId, string pkValue)
        {
            FormMetadata metadata = MetaDataServiceHelper.Load(ctx, formId) as FormMetadata;
            if (metadata == null)
                return null;
            var openParameter = CreateOpenParameter(ctx, metadata, pkValue);
            var provider = metadata.BusinessInfo.GetForm().GetFormServiceProvider();

            string importViewClass = "Kingdee.BOS.Web.Import.ImportBillView,Kingdee.BOS.Web";
            Type type = Type.GetType(importViewClass);
            IDynamicFormViewService billView = (IDynamicFormViewService)Activator.CreateInstance(type);
            billView.Initialize(openParameter, provider);
            billView.LoadData();
            return (IDynamicFormView)billView;
        }
        #endregion

    }
}
